import pretty_midi
import pygame as pg

# Create a PrettyMIDI object
cello_c_chord = pretty_midi.PrettyMIDI()

# Create an Instrument instance for a cello instrument
cello_program = pretty_midi.instrument_name_to_program('Cello')
cello = pretty_midi.Instrument(program=cello_program)


time = 0
with open('../dataset/lyrics_note/K歌之王.txt', 'r', encoding = 'utf-8') as f:
    for line in f:
        line = line.replace(',',' ')
        field = line.strip().split(' ')
        if field[0].isdigit():
            for note_number in field:
                # 逐个建立note
                note = pretty_midi.Note(velocity=100, pitch=int(note_number), start=time, end=time + 0.5)
                # 加入cello乐器中
                cello.notes.append(note)
                time += 0.5
        else:
            continue

# Add the cello instrument to the PrettyMIDI object
cello_c_chord.instruments.append(cello)
# Write out the MIDI data
cello_c_chord.write('k.mid')

print(cello_c_chord.get_pitch_class_histogram())

# # Iterate over note names, which will be converted to note number later
# for note_name in ['C5', 'E5', 'G5']:
#     # Retrieve the MIDI note number for this note name
#     note_number = pretty_midi.note_name_to_number(note_name)
#     # Create a Note instance, starting at 0s and ending at .5s
#     # velocity速度
#     note = pretty_midi.Note(
#         velocity=100, pitch=note_number, start=0, end=.5)
#     # Add it to our cello instrument
#     cello.notes.append(note)




def play_music(music_file):
  '''
  stream music with mixer.music module in blocking manner
  this will stream the sound from disk while playing
  '''
  clock = pg.time.Clock()
  # pg.mixer.init()
  try:
    pg.mixer.music.load(music_file)
    print("Music file {} loaded!".format(music_file))
  except pg.error:
    print("File {} not found! {}".format(music_file, pg.get_error()))
    return
  pg.mixer.music.play()
  print("Music file {} played!".format(music_file))
  # check if playback has finished
  while pg.mixer.music.get_busy():
    clock.tick(30)

# 初始化pg播放器
freq = 44100  # audio CD quality
bitsize = -16  # unsigned 16 bit
channels = 2  # 1 is mono, 2 is stereo
buffer = 2048  # number of samples (experiment to get right sound)
# pg.mixer.init()
pg.mixer.init(freq, bitsize, channels, buffer)


# optional volume 0 to 1.0
pg.mixer.music.set_volume(0.8)

play_music('k.mid')


# Load MIDI file into PrettyMIDI object
# midi_data = pretty_midi.PrettyMIDI('cello-C-chord.mid')
#
# # Compute the relative amount of each semitone across the entire song, 计算整个歌曲中每个半音的相对数量
# # # a proxy for key 密钥代理
# # chroma 色度，浓度
# total_velocity = sum(sum(midi_data.get_chroma()))
#
# # Shift all notes up by 5 semitones
# for instrument in midi_data.instruments:
#     # Don't want to shift drum notes
#     if not instrument.is_drum:
#         for note in instrument.notes:
#             note.pitch += 5
# # Synthesize the resulting MIDI data using sine waves
# audio_data = midi_data.synthesize()


